package com.leefine.nettysocketproxy.config;

import com.leefine.nettysocketproxy.proxy.SocketProxyServer;
import com.leefine.nettysocketproxy.support.PasswordStrategy;
import com.leefine.nettysocketproxy.support.SocketProxyServerJsonUtil;
import com.leefine.nettysocketproxy.support.ThreadHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
 * ServiceController
 *
 * Api Service
 *
 * @Author lihuai.chen@163.com
 * @Date 6/10/2021 11:59 AM
 */
@RestController
@RequestMapping("${api.path}")
public final class ServiceController {

    @PostMapping("login")
    public ApiResult<String> login(String email, String password) {
        if (email.equals(AuthInterceptorConfig.API_EMAIL) && password.equals(AuthInterceptorConfig.API_PASSWORD)) {
            return ApiResult.contruct(0, PasswordStrategy.encrypt(email + password));
        } else {
            return ApiResult.contruct(404, "Login failed!");
        }
    }

    @PostMapping("list")
    public ApiResult<List<SocketProxyServer>> list(String keyword) {
        List<SocketProxyServer> serverList;
        if (StringUtils.isBlank(keyword)) {
            serverList = SocketProxyServerJsonUtil.serverList();
        } else {
            serverList = SocketProxyServerJsonUtil.serverList();
            Iterator<SocketProxyServer> iterator = serverList.iterator();
            while (iterator.hasNext()) {
                SocketProxyServer socketProxyServer = iterator.next();
                if (!socketProxyServer.getName().contains(keyword) && !socketProxyServer.getRemoteHost().contains(keyword)) {
                    iterator.remove();
                }
            }
        }
        return ApiResult.contruct(0, serverList);
    }

    @PostMapping("state")
    public ApiResult<String> state(String name) {
        return ApiResult.contruct(0, ThreadHelper.getThreadStateByName(name));
    }

    @PostMapping("save")
    public ApiResult<String> save(SocketProxyServer socketProxyServer) {
        try {
            if (StringUtils.isAnyBlank(socketProxyServer.getName(), socketProxyServer.getRemoteHost())) {
                return ApiResult.contruct(500, "socket proxy parameter can not be empty!");
            }

            List<SocketProxyServer> serverList = SocketProxyServerJsonUtil.serverList();
            if (serverList == null)
                serverList = new ArrayList<>();

            for (SocketProxyServer proxyServer : serverList) {

                if (proxyServer.getLocalPort() == socketProxyServer.getLocalPort() ||
                        proxyServer.getName().equals(socketProxyServer.getName()) ||
                        (proxyServer.getRemoteHost().equals(socketProxyServer.getRemoteHost()) && proxyServer.getRemotePort() == socketProxyServer.getRemotePort())) {
                    return ApiResult.contruct(500, "pls check the new socket proxy,some parameter already exits!");
                }
            }
            serverList.add(socketProxyServer);
            SocketProxyServerJsonUtil.saveList(serverList);

            ThreadHelper.startThread(socketProxyServer);
            return ApiResult.contruct(0, "save and start success!");
        } catch (Exception e) {
            return ApiResult.contruct(500, e.getMessage());
        }
    }

    @PostMapping("delete")
    public ApiResult delete(String name) {
        try {
            boolean exist = false;
            List<SocketProxyServer> serverList = SocketProxyServerJsonUtil.serverList();
            Iterator<SocketProxyServer> iterator = serverList.iterator();
            while (iterator.hasNext()) {
                SocketProxyServer proxyServer = iterator.next();
                if (proxyServer.getName().equals(name)) {
                    iterator.remove();
                    exist = true;
                    break;
                }
            }
            if (exist) {
                SocketProxyServerJsonUtil.saveList(serverList);
                ThreadHelper.killThreadByName(name);

                return ApiResult.contruct(0, "delete success!");
            } else {
                return ApiResult.contruct(500, "proxy does't exist!");
            }
        } catch (Exception e) {
            return ApiResult.contruct(500, e.getMessage());
        }
    }
}